//获取应用实例
const app = getApp();
// 引入AES.js
var baseJs = require("../../common/base.js");
var gloData = app.globalData;
var codeString = '';
var useNeedAllPayRMB = 0
Page({

  /**
   * 页面的初始数据
   */
  data: {
    uid: "",
    orderid: '',
    ordernumber: '',
    buyallMa: '',
    BuyAllMaOld: '',
    buyallYoufei: '',
    // 购买的商品列表
    buygoodsList: [],
    ordertime: '',
    // 余额，微信 // 支付类型
    paytype: "",
    orderType: '0',
    payFlag: true,
    //是否展示密码输入层
    showPayPwdInput: false,
    //输入的密码
    payPasswords: "",
    //文本框焦点
    payFocus: true,
    // 授权
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    powerFlag: true,
    phoneFlag: true,
    code: 'authMSG',
    // 默认收货地址
    defaultAddress: [],
    // 弹出选择收货地址
    chooseFlag: false,
    addressData: [],
    // 新增地址
    addFlag: true,
    color: "#808080",
    region: ['', '', ''],
    // 判断 邮寄或者自提
    Type: '',
    OrderState: '0',
    surePay: '立即支付',
    DeliverGoods: 0,//是否自提
    Address: '',//地址
    show: 1,//是否显示立即支付
    useneedallpayRMB: "",//支付的现金
    useneedbuxianRMB: "",//补现
    useneedpayMaFee: "",//手续费
    useneedpayMa:"",//支付易码
    diaohuoFei: "",//调货费
    youfei: "",//邮费
    IsCanUseSetMealMa: "",//手续非是否抵扣
  },

  /**
   * 生命周期函数--监听页面加载
  */
  onLoad: function (options) {
    var uid = wx.getStorageSync('uid');
    this.setData({
      uid: uid,
      orderid: options.orderid,
      isAlreadyPayPassword: wx.getStorageSync('isAlreadyPasswords'),
      show: options.show
    })
    console.log(options);
    this.UserScanQRCodeGetOrderGoods();
    this.GetMyDefaultAddress();
    // 登录
    var that = this;
    wx.login({
      success(res) {
        //js调用登陆命令获取到code
        if (res.code) {
          codeString = res.code
          //通过code调用自己服务接口获取到openid
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      }
    })
  },
  onShow: function () {
    this.GetMyDefaultAddress();
  },

  // 授权登录
  bindAuthoriza: function () {
    var that = this;
    this.setData({
      powerFlag: false
    })
  },
  //获取授权用户的信息
  bindGetUserInfo(e) {
    wx.getSetting({
      success: res => {
        //如果经过授权
        if (res.authSetting['scope.userInfo']) {
          this.setData({
            hideBtn: true
          })
          //获取用户openid
          wx.getUserInfo({
            success: res => {
              var that = this;
              var uid = this.data.uid;
              this.data.userInfo = res.userInfo,
                this.data.userInfo.code = gloData.code,
                console.log(baseJs.api_Utils + "GetWXSmallProgeamUserOpenId/" + uid + "/" + codeString);
              wx.request({
                url: baseJs.api_Utils + "GetWXSmallProgeamUserOpenId/" + uid + "/" + codeString,
                success: function (res) {
                  console.log(res.data)
                  that.setData({
                    userInfo: app.globalData.userInfo,
                    // uid: app.globalData.userInfo.uid,
                  })
                },
                fail(res) {
                  console.log(res.data)
                }
              })

            }
          })
        }
      }
    })
  },
  // 授权登录
  powerTap: function () {
    this.setData({
      powerFlag: !this.data.powerFlag,
    })
    wx.showToast({
      title: '授权成功',
      icon: 'none',
      duration: 2000
    });
  },

  getUserInfo: function (e) {
    var that = this;
    var uid = this.data.uid;
    // console.log(e);
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      hasUserInfo: true,
    })

  },

  // App端扫收音机二维码 获取订单下的产品列表
  UserScanQRCodeGetOrderGoods: function () {
    var that = this;
    var uid = this.data.uid;
    var orderid = this.data.orderid;
    var ordernumber = this.data.ordernumber;
    var buyallMa = this.data.buyallMa;
    var BuyAllMaOld = this.data.BuyAllMaOld;
    var buyallYoufei = this.data.buyallYoufei;
    var businessname = this.data.businessname;
    var ordertime = this.data.ordertime;
    var buygoodsList = this.data.buygoodsList;
    var Type = this.data.Type;
    var OrderState = this.data.OrderState;
    // console.log(baseJs.api_Order + "UserScanQRCodeGetOrderGoods/" + uid + "/" + orderid)
    wx.request({
      url: baseJs.api_Order + "UserScanQRCodeGetOrderGoods/" + uid + "/" + orderid,
      success: function (res) {
        var json = res.data.ResultData;
        console.log(json);
        buyallMa = json.BuyAllMa;
        BuyAllMaOld = json.BuyAllMaOld;
        buyallYoufei = json.BuyAllYoufei;
        businessname = json.BusinessName;
        ordertime = json.OrderTime;
        ordernumber = json.OrderNumber;
        Type = json.DeliverGoods;
        OrderState = json.OrderState;
        // DeliverGoods=json.DeliverGoods-0
        var json1 = json.BuyGoodsList;
        for (var i = 0; i < json1.length; i++) {
          buygoodsList.push(json1[i])
        }

        that.setData({
          buyallMa: buyallMa,
          BuyAllMaOld: BuyAllMaOld,
          buyallYoufei: buyallYoufei,
          businessname: businessname,
          ordertime: ordertime,
          ordernumber: ordernumber,
          buygoodsList: buygoodsList,
          Type: Type,
          OrderState: OrderState,
        })
        wx.setStorageSync('OrderState', json.OrderState)
      },
    })
  },
  // 发送订单  
  surePay: function () {
    var that = this;
    var uid = this.data.uid;
    var orderid = this.data.orderid;
    var ordernumber = this.data.ordernumber;
    var OrderState = wx.getStorageSync('OrderState');
    console.log(OrderState)
    wx.showLoading({
      title: '加载中',
    })
    if (OrderState != '0') {
      that.setData({
        surePay: '已支付',
        payFlag: !that.data.payFlag
      })
      return;
    }
    console.log(baseJs.api_Order + "UserPayScanQRCodeOrder/" + uid + "/" + orderid)
    wx.request({
      url: baseJs.api_Order + "UserPayScanQRCodeOrder/" + uid + "/" + orderid,
      success: function (res) {
        console.log(res.data)
        wx.hideLoading();
        if (res.data.ResultFlag == 1) {
          var json = res.data.ResultData;
          console.log(json);
          var diaohuoFei = json.DiaoHuoFei;
          var couponedu = json.CouponEdu;
          var youfei = json.Youfei;
          var useNeedAllPayRMB = json.useNeedAllPayRMB
          var useneedbuxianRMB = json.useNeedBuxianRMB;
          var useneedpayMa = json.useNeedPayMa;
          var useneedpayMaFee = json.useNeedPayMaFee;
          var IsCanUseSetMealMa = json.IsCanUseSetMealMa
          that.setData({
            diaohuoFei: diaohuoFei,//调货费
            couponedu: couponedu,//优惠券额度
            useneedallpayRMB: useNeedAllPayRMB,//需要支付的现金
            youfei: youfei,//邮费
            useneedbuxianRMB: useneedbuxianRMB,//补现
            useneedpayMa: useneedpayMa,//支付的易易码
            useneedpayMaFee: useneedpayMaFee,//手续费
            IsCanUseSetMealMa: IsCanUseSetMealMa - 0,//手续费是否抵扣
            payFlag: false,
          })
          console.log(that.data.IsCanUseSetMealMa);
          // that.setData({
          //   payFlag: false,
          // })
        } else {
          wx.showToast({
            title: res.data.ResultMsg,
            icon: 'none',
            duration: 2000
          });
        }
      },
      fail(res) {
        console.log(res)
      }
    })
  },
  //余额或微信 
  radioChange: function (e) {
    this.setData({
      paytype: e.detail.value,
    });
  },
  //去支付
  goPay: function () {
    var that = this;
    var uid = this.data.uid;
    var isAlreadyPayPassword = this.data.isAlreadyPayPassword;
    var paytype = this.data.paytype;
    var orderid = this.data.orderid;
    var orderType = this.data.orderType;
    console.log(paytype)
    if (paytype == '') {
      wx.showToast({
        title: "请选择支付方式！",
        icon: 'none',
        duration: 2000
      });
      return false;
    }
    this.setData({//支付详情的弹框
      payFlag: true,
    })
      if (isAlreadyPayPassword == '1') { //是否设置支付密码
        that.setData({
          showPayPwdInput: true,
          payFocus: true
        })
      } else {
        wx.showToast({
          title: "请先去设置支付密码！",
          icon: 'none',
          duration: 1000
        });
      }
  },
  //输入密码--确定 （余额支付）
  surePasswords: function () {
    var that = this;
    var uid = this.data.uid;
    var payPasswords = this.data.payPasswords;
    var paytype = this.data.paytype;
    var orderid = this.data.orderid;
    var orderType = this.data.orderType;
    wx.request({ // 支付密码是否正确
      url: baseJs.api + baseJs.encryUrl("method=CheckMyTradePassword&UID=" + uid + "&TradePassword=" + payPasswords),
      success: function (res) {
        var json = JSON.parse(baseJs.decryUrl(res.data));
        console.log(json);
        if (json.ResultFlag == 1) { //密码正确
          console.log(paytype);
          if (paytype == 1) {//余额支付
            console.log("余额支付");
            wx.request({
              url: baseJs.api_Order + "PayOrder/" + orderid + "?" + "PayType=" + '0' + "OrderType=" + orderType,
              success: function (res) {
                console.log(res.data)
                wx.hideLoading();
                if (res.data.ResultFlag == 1) {
                  wx.showToast({
                    title: res.data.ResultMsg,
                    icon: 'none',
                    duration: 2000
                  });
                  setTimeout(function () {
                    wx.navigateTo({
                      url: '/packageA/myOrder/myOrder?type=1',
                    })
                  }, 1000)
                  that.setData({
                    showPayPwdInput: false
                  })
                } else {
                  wx.showToast({
                    title: res.data.ResultMsg,
                    icon: 'none',
                    duration: 2000
                  });
                }
              }
            })
          } else {//微信支付
            console.log("微信支付");
            wx.request({
              url: baseJs.api_Order + "PayOrder/" + orderid + "?" + "PayType=" + '3' + "&OrderType=" + orderType + "&UID=" + uid,
              success: function (res) {
                var json= res.data.ResultData
                console.log(json)
                wx.hideLoading();
                if (res.data.ResultFlag == 1) {
                  wx.requestPayment({
                    timeStamp: res.data.ResultData.timeStamp,
                    nonceStr: res.data.ResultData.nonceStr,
                    package: res.data.ResultData.package,
                    signType: res.data.ResultData.signType,
                    paySign: res.data.ResultData.paySign,
                    success(res) {
                      console.log(res);
                      wx.showToast({
                        title: '支付成功',
                        icon: 'none',
                        duration: 2000
                      });
                    },
                    fail(res) {
                      console.log(res);
                      wx.showToast({
                        title: res.err_desc,
                        icon: 'none',
                        duration: 2000
                      });
                    }
                  })
                } else {
                  wx.showToast({
                    title: res.data.ResultMsg,
                    icon: 'none',
                    duration: 2000
                  });
                }
              }
            })
          }
        } else {//密码错误
          wx.showToast({
            title: json.ResultMsg,
            icon: 'none',
            duration: 1000
          });
        }
      }
    })
  },
  // 支付弹出显示
  payShow: function () {
    this.setData({
      payFlag: !this.data.payFlag,
    })
  },

  //显示支付密码输入层
  showInputLayer: function () {
    this.setData({
      showPayPwdInput: true,
      payFocus: true,
    });
  },
  //隐藏支付密码输入层
  cancelInputPasswords: function () {
    var val = this.data.payPasswords;
    this.setData({
      showPayPwdInput: false,
      payFocus: false,
      payPasswords: '',
    });
  },
  // 获取焦点
  getFocus: function () {
    this.setData({
      payFocus: true
    });
  },
  //输入密码,监听
  inputPwd: function (e) {
    this.setData({
      payPasswords: e.detail.value
    });
  },


  // 选择收货地址
  chooseAddressTap0: function () {
    wx.navigateTo({
      url: '/packageA/address/address',
    })
    // this.GetMyAddress();
    // this.setData({
    //   chooseFlag: !this.data.chooseFlag
    // });
  },
  chooseAddressTap1: function () {
    this.setData({
      chooseFlag: !this.data.chooseFlag
    });
  },
  // 获取收货地址
  GetMyAddress: function () {
    var that = this;
    var uid = this.data.uid;
    var addressData = this.data.addressData;
    var aa = 'aabbcc';
    var bb = aa.replace('aa', '11');
    console.log(bb)
    wx.request({
      url: baseJs.api + baseJs.encryUrl("method=GetMyAddress&UID=" + uid),
      success: function (res) {
        console.log(JSON.parse(baseJs.decryUrl(res.data)));
        addressData = JSON.parse(baseJs.decryUrl(res.data)).ResultData;

        that.setData({
          addressData: addressData,

        })
      }
    })

  },
  // 新增收货地址
  addAddressTap: function () {
    this.setData({
      addFlag: !this.data.addFlag
    });
  },
  // 
  bindRegionChange: function (e) {
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      region: e.detail.value,
      color: "#333",
    })
  },
  // 
  formSubmit: function (e) {
    // console.log('form发生了submit事件，携带数据为：', e.detail.value);
    var that = this;
    var uid = this.data.uid;
    wx.request({
      url: baseJs.api + baseJs.encryUrl("method=AddAddress&UID=" + uid + "&UserName=" + e.detail.value.name + "&tel=" + e.detail.value.phone + "&Address=" + e.detail.value.area[0] + " " + e.detail.value.area[1] + " " + e.detail.value.area[2] + "&Memo=" + e.detail.value.detailAddress),
      success: function (res) {
        if (JSON.parse(baseJs.decryUrl(res.data)).ResultFlag == 1) {
          wx.showToast({
            title: JSON.parse(baseJs.decryUrl(res.data)).ResultMsg,
            icon: 'none',
            duration: 2000
          });
          setTimeout(function () {
            that.setData({
              addFlag: true,
              chooseFlag: false
            })
          }, 2000)
          that.GetMyDefaultAddress();
        } else {
          wx.showToast({
            title: JSON.parse(baseJs.decryUrl(res.data)).ResultMsg,
            icon: 'none',
            duration: 2000
          });
        }
      }
    })

  },
  // 
  formReset: function () {
    this.setData({
      addFlag: !this.data.addFlag,
    })
  },
  // 获取默认收货地址
  GetMyDefaultAddress: function () {
    var that = this;
    var uid = this.data.uid;
    var defaultAddress = this.data.defaultAddress;
    wx.request({
      url: baseJs.api + baseJs.encryUrl("method=GetMyDefaultAddress&UID=" + uid),
      success: function (res) {
        // console.log(JSON.parse(baseJs.decryUrl(res.data)));
        defaultAddress = JSON.parse(baseJs.decryUrl(res.data)).ResultData;

        that.setData({
          defaultAddress: defaultAddress,
        })
        that.filterAddress()
      }
    })
  },
  // 过滤地址
  filterAddress() {
    var that = this
    that.setData({
      Address: that.data.defaultAddress.Address
    })
    let reg = /^[\u4e00-\u9fa5]+$/i //判断是否纯文字
    let res = reg.test(this.data.Address)
    // console.log(res);
    if (!res) {
      var czy = /[^\u4e00-\u9fa5]/g
      var a = that.data.Address.replace(czy, "")
      that.setData({
        Address: a
      })
    } else {
      console.log(this.data.Address);
    }
  },


  // 设置默认地址
  setDefaultAddress: function (e) {
    var that = this;
    var uid = this.data.uid;
    console.log(e);
    var addressId = e.currentTarget.dataset.addressid;
    console.log(addressId);
    wx.request({
      url: baseJs.api + baseJs.encryUrl("method=UpDefaultAddress&UID=" + uid + "&ID=" + addressId),
      success: function (res) {
        console.log(JSON.parse(baseJs.decryUrl(res.data)));
        if (JSON.parse(baseJs.decryUrl(res.data)).ResultFlag == 1) {
          that.GetMyDefaultAddress();
          setTimeout(function () {
            that.setData({
              chooseFlag: !that.data.chooseFlag,
            })
          }, 1000)
        } else {

        }

      }
    })
  },




  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },



  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})